package ml.kupin.sso.controller;

import ml.kupin.common.constant.KuPinConstant;
import ml.kupin.common.utils.CookieUtils;
import ml.kupin.common.utils.KuPinResult;
import ml.kupin.pojo.TbUser;
import ml.kupin.sso.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户登陆Controller
 * <p>
 * Created by 小柯(Allen Kerr) on 17.5.6 10:23.
 */
@Controller
@RequestMapping("/user")
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Value("${token_cookie_name}")
    private String token_cookie_name;

    @RequestMapping("/login")
    public String showLoginPage(String redirect, Model model) {
        model.addAttribute("redirect", redirect);
        return "login";
    }

    @RequestMapping(value = "/checkLogin", method = RequestMethod.POST)
    @ResponseBody
    public KuPinResult checkLogin(TbUser user, HttpServletRequest request, HttpServletResponse response) {
        //1、 接收两个参数，调用 Service 进行登录信息检查。
        KuPinResult kuPinResult = loginService.checkLogin(user);

        //2、 从返回结果判断是否登陆成功
        if (kuPinResult.getStatus() == KuPinConstant.KuPinResult_status_success) {
            //3、登陆成功，从返回结果中取 token， 写入 cookie。注意：Cookie 要跨域。
            //Cookie 二级域名跨域需要设置:
            //          1） setDomain，设置一级域名：
            //          2） setPath，设置为 “/”
            String token = (String) kuPinResult.getData();
            CookieUtils.setCookie(request, response, token_cookie_name, token);
        }
        //返回结果
        return kuPinResult;
    }

}
